package persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AdmPersistenciaCostos {

	private static AdmPersistenciaCostos instancia;
	
	public static AdmPersistenciaCostos getInstancia() {
		if(instancia == null)
			return new AdmPersistenciaCostos();
		return instancia;
	}

	public void insert(long idCosto, long idJer, long idRol, long monto) {
		System.out.println("LOG: AdmPersistenciaCostos / insert [INICIO]");
		try{
			
			Connection con = ConectorSQL.conectar();  
			PreparedStatement ps = con.prepareStatement("insert into costos values (?,?,?,?)");
			ps.setLong(1,idCosto);
			ps.setLong(2, idRol);
			ps.setLong(3, idJer);
			ps.setLong(4, monto);
			ps.execute();
			con.close();
			System.out.println("LOG: AdmPersistenciaCostos / insert [FIN]");
		}catch(Exception e){
			System.out.println(e.getMessage());
		}	
	}

	public long generarId() {
		System.out.println("LOG: AdmPersistenciaCostos/ generarId [INICIO]");
		try{
			
			Connection con = ConectorSQL.conectar();  
			PreparedStatement ps = con.prepareStatement("select MAX(id_cos) from costos");
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				return rs.getInt(1) + 1;
			}
			con.close();
			System.out.println("LOG: AdmPersistenciaCostos / generarId [FIN]");
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return -1;
	}

	public long selectCosto(long idJer, long idRol) {
		System.out.println("LOG: AdmPersistenciaCostos/ existeCosto[INICIO]");
		try{
			
			Connection con = ConectorSQL.conectar();  
			PreparedStatement ps = con.prepareStatement("select valor from costos where id_jer = ? and id_Rol = ?");
			ps.setLong(1, idJer);
			ps.setLong(2, idRol);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				//con.close();
				System.out.println("LOG: AdmPersistenciaCostos / existeCosto [FIN]");
				return rs.getLong(1);
			}else{
				con.close();
				System.out.println("LOG: AdmPersistenciaCostos / existeCosto [FIN]");
				return -1;
			}
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return -1;
	}

	public void update(long idJer, long idRol, long valor) {
		System.out.println("LOG: AdmPersistenciaCostos / update [INICIO]");
		try{
			
			Connection con = ConectorSQL.conectar();  
			PreparedStatement ps = con.prepareStatement("update costos set valor = ? where id_rol = ? and id_jer = ?");
			ps.setLong(1,valor);
			ps.setLong(2, idRol);
			ps.setLong(3, idJer);
			ps.execute();
			con.close();
			System.out.println("LOG: AdmPersistenciaCostos / update [FIN]");
		}catch(Exception e){
			System.out.println(e.getMessage());
		}	
	}

}
